<template>
    <div class="map-wrapper">
        <div id="lbs-result"></div>
        <div id="container"></div>
        <div class="map-utils-layers">
            <Checkbox
                v-model="layerDisplay.satellite"
                @on-change="routeMapLayer('satellite')"
                >卫星图</Checkbox
            >
            <Checkbox
                v-model="layerDisplay.roadnet"
                @on-change="routeMapLayer('roadnet')"
                >路网图</Checkbox
            >
            <Checkbox
                v-model="layerDisplay.traffic"
                @on-change="routeMapLayer('traffic')"
                >实时路况</Checkbox
            >
            <Checkbox
                v-model="layerDisplay.building"
                @on-change="routeMapLayer('building')"
                >建筑楼块</Checkbox
            >
            <input
                type="text"
                id="city-name"
                v-model="cityName"
                class="map-utils-textbox"
                placeholder="输入检索的目标城市名，如“贵阳”"
                style="display:none;"
            />
            <input
                type="text"
                id="map-search"
                class="map-utils-textbox"
                v-model="keyword"
                placeholder="输入关键字，输入空格以搜索全部"
            />

            <Select v-model="type" style="width: 200px" multiple>
                <Option
                    v-for="item in typeDict"
                    :value="item.value"
                    :key="item.id"
                >
                    {{ item.value }}
                </Option>
            </Select>
            <Button type="primary" @click="searchPOI" style="margin:0 12px;" icon="ios-search">
                搜索
            </Button>
            <Button
                type="success"
                v-show="searchComplete"
                @click="configPOIData"
                icon="ios-build"
            >
                配置
            </Button>
        </div>
        <div id="mask" v-show="maskOn"></div>
    </div>
</template>

<script>
    import { busEventEmit, busEventHandle } from "@/teleport/bus";
    import jsonDownloader from "@/libs/exportJSON";
    import config from "@/config/global";

    export default {
        name: "",
        data() {
            return {
                map: null,
                maskOn: false,
                type: null,
                typeDict: [
                    {
                        id: 1,
                        value: "汽车服务",
                    },
                    {
                        id: 2,
                        value: "汽车销售",
                    },
                    {
                        id: 3,
                        value: "汽车维修",
                    },
                    {
                        id: 4,
                        value: "摩托车服务",
                    },
                    {
                        id: 5,
                        value: "餐饮服务",
                    },
                    {
                        id: 6,
                        value: "购物服务",
                    },
                    {
                        id: 7,
                        value: "生活服务",
                    },
                    {
                        id: 8,
                        value: "体育休闲服务",
                    },
                    {
                        id: 9,
                        value: "医疗保健服务",
                    },
                    {
                        id: 10,
                        value: "住宿服务",
                    },
                    {
                        id: 11,
                        value: "风景名胜",
                    },
                    {
                        id: 12,
                        value: "商务住宅",
                    },
                    {
                        id: 13,
                        value: "政府机构及社会团体",
                    },
                    {
                        id: 14,
                        value: "科教文化服务",
                    },
                    {
                        id: 15,
                        value: "交通设施服务",
                    },
                    {
                        id: 16,
                        value: "金融保险服务",
                    },
                    {
                        id: 17,
                        value: "公司企业",
                    },
                    {
                        id: 18,
                        value: "道路附属设施",
                    },
                    {
                        id: 19,
                        value: "地名地址信息",
                    },
                    {
                        id: 20,
                        value: "公共设施",
                    },
                ],
                layers: {
                    satellite: null,
                    roadnet: null,
                    traffic: null,
                    building: null,
                },
                layerDisplay: {
                    satellite: false,
                    roadnet: false,
                    traffic: false,
                    building: false,
                },
                cityName: null,
                keyword: null,
                eventHandler: {
                    click: null,
                    pathedit: null,
                    rangeedit: null,
                    searchedSelect: null,
                },
                placeSearch: null,
                searchComplete: false,
                mapFunction: {},
            };
        },
        created() {
            store.poiMaker = {
                searchData: null,
                outputData: null,
            };
        },
        mounted() {
            this.initAMap();
            this.listenPOIUpdateEvent();
        },
        methods: {
            initAMap() {
                this.map = new AMap.Map("container", {
                    mapStyle: "amap://styles/macaron",
                    zoom: 12,
                });
                store.canvas = new Array();
                AMap.plugin(
                    [
                        "AMap.MouseTool",
                        "AMap.ToolBar",
                        "AMap.Driving",
                        "AMap.Autocomplete",
                        "AMap.PlaceSearch",
                        "AMap.PolyEditor",
                        "AMap.CircleEditor",
                        "AMap.RangingTool",
                    ],
                    (e) => {
                        this.initAvailableLayer();
                    }
                );
            },
            mutantElement(formData) {
                let amapElement = this.findElementById(formData.id);
                amapElement.setExtData(formData);
                this.disableShapeEditor();
                this.enableClick(amapElement);
                this.maskOn = false;
            },
            getJustCreatedElement() {
                return store.latestDrawn;
            },
            findElementById(id) {
                return store.canvas.find((e) => {
                    return e.getExtData().id === id;
                });
            },
            disableShapeEditor() {
                this.shapeEditor.close();
            },
            enableClick(element) {
                element.setClickable(true);
            },
            disableClick(element) {
                element.setClickable(false);
            },
            setElementUpdated(element, type) {
                switch (type) {
                    case "poi":
                        let offset = new AMap.Pixel(
                            config.imageOffset[0],
                            config.imageOffset[1]
                        );
                        element.setIcon(
                            `${config.imageUrl}${msg.iconName}_marker.png`
                        );
                        element.setAnchor("top-left");
                        element.setOffset(offset);
                        element.setLabel({
                            offset: new AMap.Pixel(10, 10),
                            content: `<div class="marker-label">${msg.title}</div>`,
                            direction: "right",
                        });
                        break;
                    case "path":
                        element.setOptions({
                            strokeColor: element.getExtData().color,
                            strokeOpacity: 1,
                            strokeWeight: 10,
                            strokeStyle: "dashed",
                            showDir: true,
                        });
                        break;
                    case "range":
                        element.setOptions({
                            strokeColor: element.getExtData().color,
                            strokeOpacity: 1,
                            strokeWeight: 10,
                            strokeStyle: "dashed",
                            fillColor: element.getExtData().color,
                            fillOpacity: 0.5,
                        });
                        break;
                    case "effect":
                        element.setOptions({
                            strokeColor: "#3d8c00",
                            strokeOpacity: 1,
                            strokeWeight: 10,
                            strokeStyle: "dashed",
                            fillColor: "#3d8c00",
                            fillOpacity: 0.2,
                        });
                        break;
                }
            },

            initAvailableLayer() {
                this.layers.satellite = new AMap.TileLayer.Satellite({
                    zooms: [1, 30],
                    opacity: 1,
                    visibile: true,
                    zIndex: 4,
                });
                this.layers.roadnet = new AMap.TileLayer.RoadNet({
                    zooms: [1, 30],
                    opacity: 1,
                    visibile: true,
                    zIndex: 8,
                });
                this.layers.traffic = new AMap.TileLayer.Traffic({
                    zooms: [1, 30],
                    zIndex: 10,
                });
                this.layers.building = new AMap.Buildings({
                    zooms: [1, 30],
                    zIndex: 9,
                });
            },

            initAMapSearchService() {
                let autoOptions = {
                    input: "map-search",
                };
                let autoService = new AMap.Autocomplete(autoOptions);
                const select = (e) => {
                    this.placeSearch.setCity(e.poi.adcode);
                    this.placeSearch.search(e.poi.name); //关键字查询查询
                };
                this.placeSearch = new AMap.PlaceSearch({
                    map: this.map,
                    pageSize: 999,
                    pageIndex: 1,
                    city: this.cityName,
                    citylimit: true,
                    panel: "lbs-result",
                    autoFitView: true,
                    type: this.type ? this.type.join("|") : null,
                });
                this.placeSearch.on("markerClick", this.eventHandler.click);
                AMap.event.addListener(autoService, "select", select); //注册监听，当选中某条记录时会触发
            },
            routeMapLayer(name) {
                if (this.layerDisplay[name]) {
                    this.layers[name].setMap(this.map);
                } else {
                    this.layers[name].setMap(null);
                }
            },

            searchPOI() {
                const $this = this;
                this.initAMapSearchService();
                this.placeSearch.searchInBounds(this.keyword, this.getCurrentBounds(), (status, result) => {
                    //搜索结果
                    store.poiMaker.searchData = result.poiList.pois.map((o, i) => {
                        return {
                            id: i,
                            name: o.name,
                            type: o.type,
                            location: o.location,
                            address: o.address,
                            tel: o.tel,
                            shopinfo: o.shopinfo,
                        };
                    });
                    $this.searchComplete = true;
                });
            },
            configPOIData() {
                busEventEmit("request-config-poi");
            },
            getCurrentBounds() {
                return this.map.getBounds();
            },

            listenPOIUpdateEvent() {
                const $this = this;
                busEventHandle("request-update-poi-lbs-search", (msg) => {
                    const markers = store.poiMaker.outputData.map((o) => {
                        let m = new AMap.Marker({
                            position: [o.cargo.location.lng, o.cargo.location.lat],
                            icon: `${config.imageUrl}${o.iconName}_marker.png`,
                            offset: new AMap.Pixel(
                                config.imageOffset[0],
                                config.imageOffset[1]
                            ),
                            label: {
                                offset: new AMap.Pixel(
                                    0,
                                    -15
                                ),
                                content: `<div class="marker-label">${o.title}</div>`,
                                direction: "right",
                            },
                            anchor: "top-left",
                        });
                        $this.map.add(m);
                        return m;
                    });
                    this.map.setFitView();
                });
            },
        },
    };
</script>

<style scoped>
    #mask {
        position: fixed;
        background: #00000044;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        z-index: 99;
    }
    #container {
        width: 100vw;
        height: 100vh;
        position: fixed;
        z-index: 0;
    }
    #lbs-result {
        position: fixed;
        width: 450px;
        max-height: 80vh;
        z-index: 1;
        top: 65px;
        left: 15px;
        overflow: auto;
    }
    .map-utils-layers {
        display: flex;
        flex-flow: row nowrap;
        align-items: center;
        position: fixed;
        left: 64px;
        bottom: 16px;
        background: #fff;
        padding: 16px;
        border-radius: 6px;
        box-shadow: 0 3px 3px #00000055;
    }
    .map-utils-textbox {
        border-radius: 5px;
        border: 1px #d1d4df solid;
        width: 275px;
        padding: 5px;
        font-size: 12px;
        margin: 0 12px;
    }
    .marker-label {
        background: #000000aa;
        color: #fff;
        border: 1px #000 solid;
        border-radius: 2px;
    }
</style>